﻿using UnityEngine;  
using System.Collections;  
using UnityEditor;  
using System.IO;

/// <summary>
/// 自动生成素材的assetBundleName。生成规则：从Assets文件夹向下，文件夹 + 文件分隔符 + ...（文件夹 + 文件分隔符）+ 文件名（不含文件后缀）
/// </summary>
public class AutoSetTextureUISprite :AssetPostprocessor   
{  

	static void OnPostprocessAllAssets (string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) 
	{
		foreach (var str in importedAssets)
		{
			if(str.Contains(".") && !str.EndsWith(".cs") && !str.EndsWith(".meta") && !str.EndsWith(".asset"))
			{
				
				AssetImporter importer=AssetImporter.GetAtPath(str);
				importer.assetBundleName = CreateAssetBundleName(str);
				Debug.Log("Auto Create assetBundleName :" + importer.assetBundleName);
            }

		}
		foreach (var str in deletedAssets) 
		{
			if(str.Contains(".") && !str.EndsWith(".cs") && !str.EndsWith(".meta") && !str.EndsWith(".asset"))
			{
				AssetImporter importer=AssetImporter.GetAtPath(str);
				if(importer != null)
					importer.assetBundleName=str;
            }
        }
	}

	private static string temp_assetBundleName;

	static string CreateAssetBundleName(string path){
		temp_assetBundleName = "";
		DirectoryInfo info = new DirectoryInfo(path);
		AssetBundleNameClassification(info);
		temp_assetBundleName = temp_assetBundleName.Substring(0,temp_assetBundleName.IndexOf("."));
		return temp_assetBundleName;
	}

	static void AssetBundleNameClassification(DirectoryInfo directoryInfo){
		
		temp_assetBundleName = directoryInfo.Name + Path.DirectorySeparatorChar + temp_assetBundleName;
		DirectoryInfo info = directoryInfo.Parent;
		if(info.Name != "Assets"){
			AssetBundleNameClassification(info);
		}
	}
}  